package com.handu.luna.boss.controller;



import java.io.UnsupportedEncodingException;
import java.util.Base64;
import java.util.List;

import javax.validation.Valid;

import net.sf.json.JSONObject;

import org.springframework.data.domain.Pageable;
import org.springframework.data.web.PageableDefault;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.InitBinder;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import com.handu.luna.core.domain.BossException;
import com.handu.luna.core.domain.advertisement.AdPositionId;
import com.handu.luna.core.domain.advertisement.AdvertiseList;
import com.handu.luna.core.domain.search.AdPositionSearch;


@Controller
@RequestMapping("/advertisement/adPosition/*")
public class AdPositionIdController extends BaseController{
	
	//点击 搜索按钮
    @RequestMapping(value="index",method = RequestMethod.POST) 
    public BossModel index(AdPositionSearch adPositionSearch,@PageableDefault(page = 0,size = DEFAULT_PAGE_SIZE) Pageable pageable)throws UnsupportedEncodingException{

    	return createModel("advertisement/adPosition/index")
    			.add("adPositionSearch",adPositionSearch)
    			.add("adPositionList", new AdPositionId().findAll(adPositionSearch, pageable))
    			.add("viewState", Base64.getUrlEncoder().encodeToString(JSONObject.fromObject(adPositionSearch).toString().getBytes("UTF-8")));	
           
    }
    
    @RequestMapping(value = "index")
    public BossModel index(String viewState,@PageableDefault(page = 0,size = DEFAULT_PAGE_SIZE) Pageable pageable)throws UnsupportedEncodingException{	
    	AdPositionSearch adPositionSearch;
    	if(viewState != null && !viewState.trim().equals("") && !viewState.equals("-1")){
    	
    		//解析传递过来的查询json字符串
    		adPositionSearch = (AdPositionSearch) JSONObject.toBean(JSONObject.fromObject(new String(Base64.getUrlDecoder().decode(viewState),"UTF-8")), AdPositionSearch.class);
    		return createModel("advertisement/adPosition/index")
    				.add("adPositionSearch",adPositionSearch)
        			.add("adPositionList", new AdPositionId().findAll(adPositionSearch, pageable))
    		        .add("viewState", viewState);
    	
    	}else{
    		adPositionSearch = new AdPositionSearch();
    	    return createModel("advertisement/adPosition/index")
    	    		.add("adPositionSearch",adPositionSearch)
    			    .add("adPositionList", new AdPositionId().findAll(adPositionSearch, pageable))
    			    .add("viewState", "");	
         }
    }
    
    /*
     * 添加 
     */
	@RequestMapping(value="add")
	public BossModel add(){
	    AdPositionId adPositionId = new AdPositionId();
	    adPositionId.setAdPositionWidth(100);
	    adPositionId.setAdPositionHeight(100);
	    return createModel("advertisement/adPosition/save")
	    		.add("adPositionInfo", adPositionId);	
	}
	
	
	@RequestMapping(value="delete",method = RequestMethod.POST)
	public BossModel delete(long id,String viewState,@PageableDefault(page = 0, size = DEFAULT_PAGE_SIZE) Pageable pageable){  
	   List<AdvertiseList> advertiseList = context.getAdvertiseListRepository().findAll(id) ;//如果该广告位下面存在广告，也不允许删除该广告位！

	   if(!advertiseList.isEmpty()){
		   throw new BossException("该广告位下存在广告，不可以将其移除!"); 
	   }else{
		   context.getAdPositionIdRepository().delete(id);
	   }
		return createModel("advertisement/adPosition/adPosition_table")
				.add("adPositionList",  new AdPositionId().findAll(pageable))
				.add("viewState", viewState);
	}
	
	

	
	@RequestMapping(value="edit/{id}")
	public BossModel edit(@PathVariable long id){  
		AdPositionId adPositionId = context.getAdPositionIdRepository().findOne(id);
		/*if(adPositionId==null){
			//redirectAttributes.addFlashAttribute("message", "该广告位已被删除！");
			return createModel("advertisement/adPosition/index").add("message", "该广告位已被删除！");
		}*/
		 return createModel("advertisement/adPosition/save")
		    		.add("adPositionInfo", adPositionId);	
	}
	
	
	@RequestMapping(value="save",method = RequestMethod.POST)
	@InitBinder(value={"adPositionName","adPositionSymbol","belongPage","adPositionWidth","adPositionHeight","Description"})
	public BossModel save(@Valid final AdPositionId adPositionId,final BindingResult bindingResult,RedirectAttributes redirectAttributes)
	{
		String message = "";
		if(bindingResult.hasErrors()){
			return createModel("advertisement/adPosition/save").add("adPositionInfo", adPositionId);
		}		
		
		if(null==adPositionId.getId() && adPositionId.getAdPositionSymbol().trim()!=null && adPositionId.getBelongPage()!=null && adPositionId.getAdPositionWidth()!=0 && adPositionId.getAdPositionHeight()!=0){
			message = "添加" +adPositionId.getAdPositionName() +"成功";		
			context.getAdPositionIdRepository().save(adPositionId);
		}else if(adPositionId.getId()!=null && adPositionId.getAdPositionSymbol().trim()!=null && adPositionId.getBelongPage()!=null && adPositionId.getAdPositionWidth()!=0 && adPositionId.getAdPositionHeight()!=0){
			message = "修改" +adPositionId.getAdPositionName() +"成功";
			context.getAdPositionIdRepository().save(adPositionId);	
		}else if(adPositionId.getAdPositionName().trim()==null){
			message = "广告位名称不能为空！！";
			//bindingResult.addError(new FieldError("category", "adPositionName", message));
			//return createModel("article/category/save").add("cateParents", mall.getAllArticleCategories()); 
		}else if(adPositionId.getAdPositionSymbol().trim()==null){
			message = "广告位唯一标识不能为空！";	
		}else if(adPositionId.getBelongPage()==null){
			message = "广告位所属页面不能为空！";
		}else if(adPositionId.getAdPositionWidth()==0){
			message = "广告位宽度不能为空！";
		}else if(adPositionId.getAdPositionHeight()==0){
			message = "广告位高度不能为空！";
		}
		
		redirectAttributes.addFlashAttribute("message", message);
		return createModel("redirect:index");
		
	}
	
	//判断广告位唯一标识符 ajax
	@RequestMapping(value="check")
	public @ResponseBody boolean check(long id, String inputContent){
		return checkOnChange(id,inputContent);
	}
	
	public boolean checkOnChange(long id, String inputContent){	
		if(id!=0){
			List<AdPositionId> infoList = context.getAdPositionIdRepository().findOneBySymbol(id,inputContent.trim());
			if(!infoList.isEmpty()){
				return true;
			}
		}else{
			long adPositionId	= context.getAdPositionIdRepository().count("adPositionSymbol",inputContent.trim());
		    if(adPositionId!=0){  //String.valueOf(
			  return true;
			}
		}	
		return false;	
	}
	
	
	//编辑分类的判断
	/*@RequestMapping(value="check")
	public @ResponseBody boolean check(long id , long selectedId){
		return checkOnChange(id,selectedId);
	}
	
	public boolean checkOnChange(long id , long selectedId){
		
		List<ArticleCategory> childs = context.getArticleCategoryRepository().getAllByCatId(id);
		
		if(childs.size()>0){
			for (ArticleCategory articleCategory : childs) {
				if(articleCategory.getId() == selectedId){
					return true;
				}
			}
		}
		
		
		if(childs.size() >0){
			for (ArticleCategory articleCategory : childs) {
				if(checkOnChange(articleCategory.getId(), selectedId)){
					return true;
				}
			}
		}		
		return false;
	}*/
	

}
